package cgo

import (
	"bufio"
	"encoding/json"
	"errors"
	"go/parser"
	"go/token"
	"io"
	"io/fs"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strings"
)

// AnalyzeCgo scans projectDir to detect usage of cgo (import "C") and collects
// dynamic library dependencies. The resulting list is written to cgo_deps.json
// under projectDir and also returned.
func AnalyzeCgo(projectDir string) ([]string, error) {
	if projectDir == "" {
		return nil, errors.New("projectDir is empty")
	}

	hasCgo, err := containsCImport(projectDir)
	if err != nil {
		return nil, err
	}
	if !hasCgo {
		return nil, nil
	}

	// gather dependency directories via `go list`
	dirs, err := listDepDirs(projectDir)
	if err != nil {
		return nil, err
	}

	libs := make(map[string]struct{})
	for _, dir := range dirs {
		entries, err := os.ReadDir(dir)
		if err != nil {
			continue
		}
		for _, e := range entries {
			if e.IsDir() || !strings.HasSuffix(e.Name(), ".so") {
				continue
			}
			soPath := filepath.Join(dir, e.Name())
			libs[soPath] = struct{}{}
			if deps, err := soDeps(soPath); err == nil {
				for _, d := range deps {
					libs[d] = struct{}{}
				}
			}
		}
	}

	var result []string
	for p := range libs {
		result = append(result, p)
	}
	sort.Strings(result)

	data, err := json.MarshalIndent(result, "", "  ")
	if err != nil {
		return nil, err
	}
	if err := os.WriteFile(filepath.Join(projectDir, "cgo_deps.json"), data, 0644); err != nil {
		return nil, err
	}

	return result, nil
}

// containsCImport reports whether any Go file under dir imports "C".
func containsCImport(dir string) (bool, error) {
	found := false
	err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if d.IsDir() {
			return nil
		}
		if filepath.Ext(path) != ".go" {
			return nil
		}
		fset := token.NewFileSet()
		f, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly)
		if err != nil {
			return err
		}
		for _, imp := range f.Imports {
			if strings.Trim(imp.Path.Value, "\"") == "C" {
				found = true
				return io.EOF
			}
		}
		return nil
	})
	if err != nil && !errors.Is(err, io.EOF) {
		return false, err
	}
	return found, nil
}

// listDepDirs runs `go list -deps -f '{{.Dir}}'` and returns unique directories.
func listDepDirs(dir string) ([]string, error) {
	cmd := exec.Command("go", "list", "-deps", "-f", "{{.Dir}}", "./...")
	cmd.Dir = dir
	out, err := cmd.Output()
	if err != nil {
		return nil, err
	}
	lines := strings.Split(string(out), "\n")
	seen := make(map[string]struct{})
	var dirs []string
	for _, l := range lines {
		l = strings.TrimSpace(l)
		if l == "" {
			continue
		}
		if _, ok := seen[l]; !ok {
			seen[l] = struct{}{}
			dirs = append(dirs, l)
		}
	}
	return dirs, nil
}

// soDeps extracts shared library dependencies for path using ldd or objdump.
func soDeps(path string) ([]string, error) {
	if deps, err := runLdd(path); err == nil {
		return deps, nil
	}
	return runObjdump(path)
}

func runLdd(path string) ([]string, error) {
	cmd := exec.Command("ldd", path)
	out, err := cmd.Output()
	if err != nil {
		return nil, err
	}
	var deps []string
	scanner := bufio.NewScanner(strings.NewReader(string(out)))
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" || strings.Contains(line, "not found") {
			continue
		}
		if strings.Contains(line, "=>") {
			fields := strings.Fields(line)
			for i := 0; i < len(fields)-1; i++ {
				if fields[i] == "=>" {
					p := fields[i+1]
					if strings.HasPrefix(p, "/") {
						deps = append(deps, p)
					}
					break
				}
			}
		} else if strings.HasPrefix(line, "/") {
			// lines like: /lib64/ld-linux-x86-64.so.2 (0x00007f...)
			fields := strings.Fields(line)
			if len(fields) > 0 && strings.HasPrefix(fields[0], "/") {
				deps = append(deps, fields[0])
			}
		}
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return deps, nil
}

func runObjdump(path string) ([]string, error) {
	cmd := exec.Command("objdump", "-p", path)
	out, err := cmd.Output()
	if err != nil {
		return nil, err
	}
	var deps []string
	scanner := bufio.NewScanner(strings.NewReader(string(out)))
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if strings.HasPrefix(line, "NEEDED") {
			fields := strings.Fields(line)
			if len(fields) > 1 {
				deps = append(deps, fields[1])
			}
		}
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return deps, nil
}
